/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net.testutil;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class SimpleSocketEchoClient {
    private SocketChannel channel;

    public SimpleSocketEchoClient(SocketAddress localAddress) throws IOException {
        channel = SocketChannel.open();
        channel.configureBlocking(true);
        channel.socket().setReuseAddress(true);
        channel.socket().bind(localAddress);
    }

    public SimpleFuture connect(final SocketAddress remoteAddress) throws Exception {
        final SimpleFuture future = new SimpleFuture();
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.submit(new Runnable() {
            public void run() {
                try {
                    channel.connect(remoteAddress);
                    future.set(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        return future;
    }

    public SimpleFuture send(String message) throws IOException {
        byte[] bytes = message.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        channel.write(buffer);

        return receive();
    }

    public SimpleFuture receive() {
        final SimpleFuture future = new SimpleFuture();
        final ByteBuffer buffer = ByteBuffer.allocate(1024);

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.submit(new Runnable() {
            public void run() {
                try {
                    channel.read(buffer);
                    byte[] bytes = new byte[buffer.position()];
                    buffer.flip();
                    buffer.get(bytes);
                    future.set(new String(bytes));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        return future;
    }

    public void close() {
        try {
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
